package cn.edu.nju.ws.aquila.ui.servlets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.nju.ws.aquila.database.DBConnectionFactory;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String uid = request.getParameter("uid");
		String pwd = request.getParameter("pwd") ;
		if(uid==null||pwd==null){
			request.setAttribute("message", "error") ;
			request.getRequestDispatcher("./login.jsp").forward(request,response) ;
		}
		Connection con = DBConnectionFactory.getConnection();
		try {
			PreparedStatement ps = con.prepareStatement("select id from usr where name=?");
			ps.setString(1, uid.trim()) ;
			ResultSet rs = ps.executeQuery();
			if(rs.next()){
				request.setAttribute("message", "userExist") ;
				request.getRequestDispatcher("./register.jsp").forward(request, response) ;
				
			}else{
				PreparedStatement newUserPs =con.prepareStatement("insert into usr(name,pwd) values(?,?)"); 
				String name = uid.trim();
				String password = pwd;
				newUserPs.setString(1, name) ;
				newUserPs.setString(2, password) ;
				newUserPs.executeUpdate();
				request.getSession().setAttribute("user", name) ;
				request.getRequestDispatcher("./main_datasource.jsp").forward(request, response) ;
				newUserPs.close();
			}
			rs.close();
			ps.close();
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}    
	}

}
